/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package earleyalgorithm;

import java.util.Arrays;
/**
 *
 * @author NGOC
 */
public class Rule {
    Category left;
    Category[] right;

    public Rule(Category left, Category... right) {
	if(left == null) {
            throw new IllegalArgumentException("empty left category");
	}
	if(left.terminal) {
            throw new IllegalArgumentException("left category is terminal");
	}
	if(right == null || right.length == 0) {
            throw new IllegalArgumentException("no right categories");
	}

	// check for nulls on right
	for(Category r : right) {
            if(r == null) {
		throw new IllegalArgumentException(
                    "right contains null category: " + Arrays.toString(right));
		}
            }

            this.left = left;
            this.right = right;
	}

	public Category getLeft() {
            return left;
	}

	public Category[] getRight() {
            return right;
	}

	public boolean isPreterminal() {
            for(Category r : right) {
		if(r.terminal) {
                    return true;
		}
            }
            return false;
	}

	public boolean isSingletonPreterminal() {
            return (isPreterminal() && right.length == 1);
	}

	
	@Override
	public boolean equals(Object obj) {
            if(obj instanceof Rule) {
		Rule or = (Rule)obj;
		return (left.equals(or.left) && Arrays.equals(right, or.right));
            }

            return false;
	}

	@Override
	public int hashCode() {
            return (31 * left.hashCode() * Arrays.hashCode(right));
	}

	@Override
	public String toString() {
            StringBuilder sb = new StringBuilder(left.toString());
            sb.append(" ->");

            for(int i = 0; i < right.length; i++) {
                   sb.append(' '); // space between categories
                   sb.append(right[i].toString());
            }

            return sb.toString();
	}
}
